<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import LookVoucherPop from '@/pages/allOrder/lookVoucherPop.vue';
import PayMessagePop from '@/pages/allOrder/payMessagePop.vue';
import AfterSalePop from '@/pages/allOrder/afterSalePop.vue';
import consts from '@/consts.ts';
import {
  addAgainPost,
  cancelOrderPost,
  confirmReceiptPost,
  orderDetailsGet,
  paymentVoucherPost,
  uploadPost,
} from '@/services/my.ts';
import type { OrderDetail } from '@/types';
import type { UploaderFileListItem } from 'vant';

const $route = useRoute();
const $router = useRouter();
const detailData = reactive({
  orderDetail: {} as OrderDetail,
  payMessage: {
    supplierName: '',
    bankAccount: '',
    depositBank: '',
    orderId: '',
    isChange: false,
  },
});
const orderStatus = computed(() => {
  return consts.orderStatus[detailData.orderDetail.orderStatus as keyof typeof consts.orderStatus];
});

const onCancelClick = async () => {
  const { err, message } = await cancelOrderPost({
    orderId: detailData.orderDetail.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  showToast(message);
};
const onAgainOrderClick = async () => {
  const { err } = await addAgainPost({
    orderId: detailData.orderDetail.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  $router.push({ path: '/car' });
};
const onAfterDetailClick = () => {
  $router.push({
    path: '/afterSales',
    query: {
      orderId: detailData.orderDetail.orderId,
    },
  });
};
const onConfirmShopClick = async () => {
  const { err, message } = await confirmReceiptPost({
    orderId: detailData.orderDetail.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  showToast(message);
};
const payMessagePop = ref(false);
const onPayMessageClick = () => {
  payMessagePop.value = true;
};

// 上传凭证
const upVoucherPop = ref(false);
const voucherImg = ref<UploaderFileListItem[]>([]);
const onUpVoucherClick = () => {
  // 清除数据
  voucherImg.value = [];
  detailData.payMessage.isChange = !!detailData.orderDetail.payProof;
  if (detailData.orderDetail.payProof) {
    voucherImg.value = detailData.orderDetail.payProof.split(',').map((item: any) => {
      return {
        url: item,
      };
    });
  }
  upVoucherPop.value = true;
};
const onVoucherSubClick = async () => {
  if (!voucherImg.value[0]?.url) {
    showToast('请上传凭证');
    return;
  }
  const { err, message } = await paymentVoucherPost({
    orderId: detailData.payMessage.orderId,
    payProof: voucherImg.value[0].url,
    isChange: detailData.payMessage.isChange,
  });
  if (err) {
    showToast(err);
    return;
  }
  upVoucherPop.value = false;
  showToast(message);
};

// 查看凭证
const lookVoucherPop = ref(false);
const lookVoucherImg = ref('');
const onLookVoucherClick = () => {
  lookVoucherImg.value = detailData.orderDetail.payProof;
  lookVoucherPop.value = true;
};

// 上传图片处理
const beforeRead = (file: any) => {
  const isJPG =
    file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
  const isLt1M = file.size / 1024 / 1024 < 10;
  if (!isJPG) {
    showToast('只能上传jpg/png/jpeg文件!');
  }
  if (!isLt1M) {
    showToast('上传图片大小不能超过 10MB!');
  }
  return isJPG && isLt1M;
};
const afterRead = async (file: any) => {
  file.status = 'uploading';
  file.message = '上传中...';
  const formData = new FormData();
  formData.append('file', file.file);
  const { err, data } = await uploadPost(formData);
  if (err) {
    file.status = 'failed';
    file.message = '上传失败';
  } else {
    file.status = 'done';
    file.message = '上传成功';
    voucherImg.value = [{ url: data }];
  }
};

// 售后
const afterSalePop = ref(false);
const afterOrderId = ref('');
const onAfterClick = () => {
  afterSalePop.value = true;
  afterOrderId.value = detailData.orderDetail.orderId;
};
const loadData = async () => {
  const { data, err } = await orderDetailsGet({
    orderId: $route.query.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  detailData.orderDetail = data.data;
  detailData.payMessage.supplierName = data.data.supplierName;
  detailData.payMessage.bankAccount = data.data.bankAccount;
  detailData.payMessage.depositBank = data.data.depositBank;
  detailData.payMessage.orderId = data.data.orderId;
};
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="detail-container">
    <div class="top">
      <div class="top-icon">
        <svg-icon icon-class="shop" size="1.4em" />
        <div class="icon-status">{{ orderStatus }}</div>
      </div>
      <div class="top-text" v-if="detailData.orderDetail.orderStatus === 'DELIVERED'">
        物流单号：{{ detailData.orderDetail.trackingNumber }}
      </div>
    </div>
    <div class="detail-address">
      <svg-icon icon-class="address-local" size="1.1em" />
      <div class="address-text">
        <div>{{ detailData.orderDetail.shippingDetail }}</div>
        <div class="address-name">
          {{ `${detailData.orderDetail.shippingPerson}  ${detailData.orderDetail.shippingMobile}` }}
        </div>
      </div>
    </div>
    <div class="order-box">
      <div class="box-title">
        <div class="title-left">
          <svg-icon icon-class="shop" size="1.3em" />
          <div class="title-text">{{ detailData.orderDetail.supplierName }}</div>
          <svg-icon icon-class="right" size="1em" />
        </div>
        <div class="title-right">{{ orderStatus }}</div>
      </div>
      <div
        class="goods_box"
        v-for="orderItem in detailData.orderDetail.orderGoodsList"
        :key="orderItem.goodsId"
      >
        <van-image :src="orderItem.goodsImg?.split(',')[0]" round />
        <div class="goods_spc">
          <div class="goods_name">{{ orderItem.goodsName }}</div>
          <div class="goods_level">{{ orderItem.goodsSpec }}</div>
        </div>
        <div class="goods_price">
          <div class="price_num curPrice">{{ `￥${orderItem.discountPrice}` }}</div>
          <div class="price_num disPrice">{{ `￥${orderItem.price}` }}</div>
          <div class="price_num amount">{{ `x ${orderItem.amount}` }}</div>
        </div>
      </div>
      <div class="order-price">
        <div class="total-price">
          合计金额：
          <span>{{ `￥ ${detailData.orderDetail.orderPrice}` }}</span>
        </div>
        <div class="disPrice">
          <span>折后金额：</span>
          <span>￥</span>
          <span class="dis-icon">{{ `${detailData.orderDetail.orderReceivePrice}` }}</span>
        </div>
      </div>
    </div>
    <van-field
      :model-value="detailData.orderDetail.orderCode"
      class="custom-field"
      label="订单编号"
      type="textarea"
      rows="1"
      autosize
      readonly
    />
    <van-field
      :model-value="detailData.orderDetail.createTime"
      class="custom-field"
      label="创建时间"
      type="textarea"
      rows="1"
      autosize
      readonly
    />
    <van-field
      :model-value="detailData.orderDetail.buyerRemark"
      class="custom-field"
      label="备注"
      type="textarea"
      rows="1"
      autosize
      readonly
    />
  </div>
  <van-action-bar placeholder>
    <template #default>
      <div class="action-box">
        <van-button
          v-if="detailData.orderDetail.orderStatus === 'UNPAID'"
          @click="onCancelClick"
          class="infoButton"
          text="取消订单"
        />
        <van-button
          v-if="detailData.orderDetail.orderStatus === 'COMPLETED'"
          @click="onPayMessageClick"
          class="infoButton"
          text="收款信息"
        />
        <van-button
          v-if="detailData.orderDetail.orderStatus === 'UNPAID'"
          @click="onUpVoucherClick"
          class="colorButton"
          text="上传凭证"
        />
        <van-button
          class="colorButton"
          v-if="
            detailData.orderDetail.orderStatus === 'CANCELED' ||
              detailData.orderDetail.orderStatus === 'COMPLETED'
          "
          @click="onAgainOrderClick"
          text="再来一单"
        />
        <van-button
          v-if="
            ['UNDELIVER', 'DELIVERED', 'COMPLETED', 'APPLY'].includes(
              detailData.orderDetail.orderStatus,
            )
          "
          class="colorButton"
          @click="onLookVoucherClick"
          text="查看凭证"
        />
        <van-button
          v-if="
            (detailData.orderDetail.orderStatus === 'UNDELIVER' ||
              detailData.orderDetail.orderStatus === 'DELIVERED') &&
              (detailData.orderDetail.afterSaleFlag === 'NOT_APPLY' ||
                detailData.orderDetail.afterSaleFlag === 'CANCELED')
          "
          @click="onAfterClick"
          class="infoButton"
          text="申请售后"
        />
        <van-button
          v-if="
            ['APPLY', 'AFTERSALEING', 'COMPLETED'].includes(detailData.orderDetail.afterSaleFlag)
          "
          class="infoButton"
          @click="onAfterDetailClick"
          text="售后详情"
        />
        <van-button
          v-if="
            detailData.orderDetail.orderStatus === 'PAYAUDIT' ||
              detailData.orderDetail.orderStatus === 'PAYREJECT'
          "
          @click="onUpVoucherClick"
          class="infoButton"
          text="更换凭证"
        />
        <van-button
          v-if="detailData.orderDetail.orderStatus === 'DELIVERED'"
          @click="onConfirmShopClick"
          class="colorButton"
          text="确认收货"
        />
      </div>
    </template>
  </van-action-bar>
  <van-popup v-model:show="upVoucherPop" position="bottom" :style="{ maxHeight: '70%' }">
    <div class="voucher-popup some-popup">
      <div class="pay-text">收款信息</div>
      <div class="pay-icon">
        <svg-icon icon-class="shop" size="1.3em" />
        <span>{{ detailData.payMessage.supplierName }}</span>
      </div>
      <van-field
        class="custom-field"
        label="收款人"
        :model-value="detailData.payMessage.supplierName"
        type="textarea"
        rows="1"
        autosize
        readonly
      />
      <van-field
        class="custom-field"
        label="收款账户"
        :model-value="detailData.payMessage.depositBank"
        type="textarea"
        rows="1"
        autosize
        readonly
      />
      <van-field
        class="custom-field"
        label="收款银行"
        :model-value="detailData.payMessage.bankAccount"
        type="textarea"
        rows="1"
        autosize
        readonly
      />
      <van-field class="up-lable" label="上传凭证" placeholder="请上传凭证">
        <template #input>
          <van-uploader
            v-model="voucherImg"
            preview-size="5em"
            :before-read="beforeRead"
            :after-read="(file: any) => afterRead(file)"
            :max-count="1"
          >
            <template #default>
              <div class="upload-style">
                <svg-icon icon-class="uploader" size="1.4em" />
              </div>
            </template>
          </van-uploader>
        </template>
        <template #extra>
          <div class="upload-tip">只能上传jpg/png文件，且不超过10MB</div>
        </template>
      </van-field>
      <div class="voucher-bottom">
        <van-button color="#E89000" @click="upVoucherPop = false" plain round text="返回" />
        <van-button color="#E89000" @click="onVoucherSubClick" round text="提交" />
      </div>
    </div>
  </van-popup>
  <!-- 查看凭证 -->
  <LookVoucherPop v-model="lookVoucherPop" :look-voucher-img="lookVoucherImg" />
  <!-- 收款信息 -->
  <PayMessagePop v-model="payMessagePop" :payMessage="detailData.payMessage" />
  <!-- 售后 -->
  <AfterSalePop v-model="afterSalePop" :order-id="afterOrderId" />
</template>

<style scoped lang="scss">
.detail-container {
  width: 100%;
  min-height: 100%;
  background: #f6f6f6;

  .top {
    width: 100%;
    height: 48px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    font-weight: 500;
    color: #e86600;
    background: #fff;

    .top-icon {
      display: flex;
      align-items: center;

      .icon-status {
        margin-left: 8px;
      }
    }

    .top-text {
      font-size: 14px;
      font-weight: 400;
      color: #00000080;
    }
  }

  .detail-address {
    width: 100%;
    height: 66px;
    padding: 0 16px;
    display: flex;
    background: #fff;

    .address-text {
      font-size: 16px;
      font-weight: 500;
      margin-left: 8px;
      color: #222222;

      .address-name {
        font-size: 14px;
        font-weight: 400;
        margin-top: 8px;
        color: #787878;
      }
    }
  }

  .box-title {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title-left {
      display: flex;
      align-items: center;

      .title-text {
        font-size: 13px;
        font-weight: 500;
        margin-left: 8px;
        color: #222222;
      }
    }

    .title-right {
      font-size: 14px;
      font-weight: 400;
      color: #e86600;
    }
  }

  .order-box {
    width: 100%;
    background: white;
    padding: 0 16px;
    margin-top: 8px;

    .goods_box {
      width: 100%;
      height: 104px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #fff;

      .van-image {
        width: 88px;
        height: 88px;
        border-radius: 8px;
      }

      .goods_spc {
        width: 170px;
        height: 100%;
        padding-top: 8px;

        .goods_name {
          width: 100%;
          font-size: 13px;
          font-weight: 500;
          color: #000000;
          // 超过一行就显示省略号
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .goods_level {
          width: 100%;
          font-size: 12px;
          font-weight: 400;
          margin-top: 3px;
          color: #787878;
          // 超过三行就显示省略号
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .goods_price {
        height: 100%;
        padding-top: 8px;

        .price_num {
          display: flex;
          justify-content: flex-end;
        }

        .curPrice {
          font-size: 14px;
          font-weight: 500;
        }

        .disPrice {
          font-size: 12px;
          font-weight: 400;
          color: #aaaaaa;
          text-decoration: line-through;
        }

        .amount {
          font-size: 10px;
          font-weight: 400;
          color: #aaaaaa;
        }
      }
    }

    .order-price {
      width: 100%;
      height: 24px;
      font-size: 12px;
      font-weight: 400;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .total-price {
        color: #787878;

        span {
          text-decoration: line-through;
        }
      }

      .disPrice {
        margin-left: 12px;
        display: flex;
        align-items: center;
        color: #222222;

        .dis-icon {
          font-size: 16px;
        }
      }
    }
  }
}

.some-popup {
  width: 100%;
  background: #ffffff;
  padding: 0 16px;

  .pay-text {
    width: 100%;
    height: 40px;
    font-size: 14px;
    font-weight: 500;
    color: #000000;
    display: flex;
    align-items: center;
  }

  .pay-icon {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;

    span {
      margin-left: 8px;
      font-size: 13px;
      font-weight: 500;
      color: #000000;
    }
  }

  :deep(.van-field__control) {
    color: #222222;
    font-size: 13px;
    font-weight: 400;
  }

  :deep(.van-field__label) {
    color: #787878;
    font-size: 13px;
    font-weight: 400;
  }
}

.voucher-popup {
  :deep(.van-button--normal) {
    width: 160px;
    height: 40px;
    margin: 20px 0;
  }

  //:deep(.van-uploader) {
  //  width: 64px;
  //  height: 64px;
  //}

  .up-lable {
    :deep(.van-field__label) {
      font-size: 14px;
      font-weight: 500;
      color: #222222;
    }
  }

  .upload-tip {
    font-size: 12px;
    font-weight: 400;
    color: #787878;
    margin-left: 92px;
  }

  .voucher-bottom {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

:deep(.van-field__control) {
  font-size: 13px;
  font-weight: 400;
  color: #aaaaaa;
}

.action-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  //flex-direction: row-reverse; /* 新增这行实现水平翻转 */
  justify-content: flex-end;

  :deep(.van-button) {
    padding: 0 12px;
    height: 36px;
    margin: 0 6px;
  }

  :deep(.van-button__text) {
    font-size: 13px;
    font-weight: 500;
  }

  .infoButton {
    color: #454545;
    background: #f6f6f6;
  }

  .colorButton {
    color: #e86600;
    background: #e8900033;
  }
}
</style>
